#!/bin/bash

# Check if user is root
if [ $(id -u) != "0" ]; then
    printf "Error: You must be root to run this script!\n"
    exit 1
fi

printf "\n"
printf "==========================\n"
printf " Nginx 1.6.0 Install	  \n"
printf "==========================\n"
printf "\n\n"

if [ ! -s websrc ]; then    
    printf "Error: directory websrc not found.\n"
    exit 1
fi

cd websrc

printf "\n========= source package download start =========\n\n"

if [ -s pcre-8.34.zip ]; then
    echo "pcre-8.34.zip [found]"
else
    echo "pcre-8.34.zip download now..."
    wget http://ncu.dl.sourceforge.net/project/pcre/pcre/8.34/pcre-8.34.zip
fi

if [ -s nginx-1.6.0.tar.gz ]; then
    echo "nginx-1.6.0.tar.gz [found]"
else
    echo "nginx-1.6.0.tar.gz download now..."
    wget http://nginx.org/download/nginx-1.6.0.tar.gz
fi

nginxMd5=`md5sum nginx-1.6.0.tar.gz | awk '{print $1}'`
if [ "$nginxMd5" != "8efa354f1c3c2ccf434a50d3fbe82340" ]; then
    echo "Error: nginx-1.6.0.tar.gz package md5 value is invalid. Please check package download url";
    exit 1
fi

if [ -s pcre-8.34 ]; then
    rm -rf pcre-8.34    
fi
unzip pcre-8.34.zip

if [ -s nginx-1.6.0 ]; then
    rm -rf nginx-1.6.0
fi
tar zxvf nginx-1.6.0.tar.gz

printf "\n========= source package download completed =========\n\n"

groupadd www
useradd -g www www -s /bin/false

mkdir -p /www
chown -R www:www /www
chmod 0755 -R /www

printf "========= pcre install start... =========\n\n"

cd pcre-8.34
./configure --prefix=/usr/local/pcre
make
make install
cd -

printf "\n========== pcre install end =============\n\n"
printf "========= Nginx install start... =========\n\n"

cd nginx-1.6.0
./configure --prefix=/usr/local/nginx --user=www --group=www --without-http_memcached_module --with-http_stub_status_module --with-http_ssl_module --with-file-aio --with-http_sub_module --with-http_realip_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_image_filter_module --with-pcre=../pcre-8.34
make
make install
cd -

cp ../nginx.rcd.txt /etc/rc.d/init.d/nginx
chmod 0755 /etc/rc.d/init.d/nginx

service nginx start
chkconfig nginx on

printf "\n========== Nginx install Completed! =======\n\n"
printf "============== The End. ==============\n"